import store from '../store/index.js'
import { baseApiUrl } from '../config.js'
const ApiUrl = baseApiUrl  // 基础路径

let Prohibited = false

var globalPostRequest = function (obj) { //接口路径，数据，回调函数，是否post或get请求
	var url = ApiUrl + obj.url
	// #ifdef H5
	url = ApiUrl + obj.url
	// #endif
	var data = obj.data
	var method = obj.method.toLocaleUpperCase()
	var callback = obj.callback
	var arraybuffer = obj.arraybuffer

	var header = obj.header || {
		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息,
	}

	// 不需要使用登录成功的 角色token的接口
	//! 获取用户信息的接口直接使用登录回调的token，因为获取用户信息失败将视为登录失效，故token及用户信息将在获取用户信息成功后记录并视为登录成功
	var unnecessaryTokenApi = [
		'/login',
		'/captchaImage',
		'/system/user/getInfo',
		'/modules/area/tree'
	]

	if (unnecessaryTokenApi.indexOf(obj.url) === -1) {
		header = Object.assign({}, header, {
			Authorization: store.state.login.userInfo.token || ''
		})
	}

	let requestName = 'requestTask' + JSON.stringify(url);
	let timeout = obj.timeout || 60000;
	requestName = uni.request({
		url: url,
		data: data,
		method: method,
		dataType: 'json',
		responseType: arraybuffer,
		timeout: timeout,
		header: header,
		success: (res) => {
			if (res.data.code == 401) {
				uni.showToast({
					title: '认证失败，无法访问系统资源',
					mask: false,
					icon: "none",
					duration: 1500
				});
				if(!Prohibited) {
					setTimeout(()=> {
						Prohibited = true
						store.commit('loginErr_logout')
					},1000)
				}
				var data = null
				callback(data)
			}
			if (res.statusCode === 200) {
				callback(res.data)

			} else if (res.statusCode == 400) {
				uni.showToast({
					title: '请求接口错误',
					mask: false,
					icon: "none",
					duration: 1500
				});
				var data = null
				callback(data)

			} else if (res.statusCode == 404) {
				uni.showToast({
					title: '请求接口错误',
					icon: "none",
					mask: false,
					duration: 1500
				});
				var data = { "code": "404", "message": "请求接口错误" }
				callback(data)

			} else if (res.statusCode == 408) {
				uni.showToast({
					title: '请求超时',
					icon: "none",
					mask: false,
					duration: 1500
				});
				var data = { "code": "408", "message": "请求超时" }
				callback(data)

			} else if (res.statusCode == 500) {
				uni.showToast({
					title: '服务器内部错误',
					icon: "none",
					mask: false,
					duration: 1500
				});
				var data = { "code": "500", "message": "服务器内部错误" }
				callback(data)

			} else if (res.statusCode == 504) {
				uni.showToast({
					title: '连接服务器超时',
					icon: "none",
					mask: false,
					duration: 1500
				});
				var data = { "code": "504", "message": "连接服务器超时" }
				callback(data)
			}
		},
		fail: (error) => {
			callback(error)
			uni.showToast({
				title: "网络连接异常,请稍后重试",
				icon: "none",
			})
		},
		
	})
	
}
export default globalPostRequest